/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.compomics.fspike.contentprovider.fastaproviders.impl;

import com.compomics.fspike.fastaprocessing.FastaProcessing;
import com.compomics.dbtoolkit.toolkit.TranslateDB;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;

/**
 *
 * @author Kenneth
 */
public class NucleotideFastaProvider extends DefaultFastaProvider {

    private File tempCodonTableFile;
    private final File inputFile;
    private final int maxPepLength;
    private final int minPepLength;

    /**
     *
     * @param inputFile the input genomic fasta
     * @param minPepLength the minimum length of sequences to retain
     * @param maxPepLength the maximum length of sequences to retain
     */
    public NucleotideFastaProvider(File inputFile, int minPepLength, int maxPepLength) {
        this.inputFile = inputFile;
        this.minPepLength = minPepLength;
        this.maxPepLength = maxPepLength;
    }

    @Override
    public File getCleanFastaFile() throws Exception {
//prepare the codontable for translation

        if (tempCodonTableFile == null) {
            if (dialog != null) {
                dialog.appendReport("Initiating codon table", true, true);
            }
            loadDefaultCodonTableFile();
        }
        cleanFastaFile = new File(inputFile.getName().replace("." + FilenameUtils.getExtension(inputFile.getName()), "") + "_translated.fasta");

        if (!cleanFastaFile.exists()) {
            //construct the command line arguments for dbToolkit
            String[] args = new String[]{
                "--cut", tempCodonTableFile.getAbsolutePath(),
                "--input", inputFile.getAbsolutePath(),
                cleanFastaFile.getAbsolutePath()
            };
            //translate the db
            if (dialog != null) {
                dialog.appendReport("Translating genomic fasta file", true, true);
                dialog.setSecondaryProgressCounterIndeterminate(true);
            }
            TranslateDB.main(args);
            //because the fasta entries generated by both dbToolkit and some nucleotidefastas contain linebreaks...
            //this also can take care of headers...;
            if (dialog != null) {
                dialog.appendReport("Removing stop codon markers in protein sequences", true, true);
            }
            FastaProcessing.removeStopCodonsAndLineBreaks(cleanFastaFile, minPepLength, maxPepLength);
            if (dialog != null) {
                dialog.appendReport("Translating genomic fasta file", true, true);
                dialog.setSecondaryProgressCounterIndeterminate(false);
                dialog.resetSecondaryProgressCounter();
            }
        }
        //save as a spiked fasta to add the spikes to, in case the user wants to save the clean one as well
        spikedFasta = new File(cleanFastaFile.getAbsolutePath().replace(".fasta", "_spiked.fasta"));
        FileUtils.copyFile(cleanFastaFile, spikedFasta);
        setContaminatedFastaFile(spikedFasta);
        return cleanFastaFile;
    }

    //loads the codontable from within the jar...
    private void loadDefaultCodonTableFile() throws IOException {
        if (tempCodonTableFile == null) {
            tempCodonTableFile = File.createTempFile("codontable", ".txt");
            InputStream inputStream = new ClassPathResource("codontable.txt").getInputStream();
            OutputStream outputStream = new FileOutputStream(tempCodonTableFile);
            IOUtils.copy(inputStream, outputStream);
            tempCodonTableFile.deleteOnExit();
        }
    }

    /**
     * convenience method in case the user wants to translate something else
     * (not yet implemented)
     *
     * @param codonTable
     * @throws IOException
     */
    public void loadCodonTableFile(File codonTable) throws IOException {
        tempCodonTableFile = codonTable;
    }

}
